package com.ldcc.springcomponentdemo.spring_integration.poller;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.integration.annotation.Poller;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.QueueChannel;
import org.springframework.integration.config.EnableIntegration;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.PollableChannel;
import org.springframework.messaging.support.GenericMessage;

import java.util.Scanner;

@SpringBootApplication
@EnableIntegration
public class SpringIntegrationPollerDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringIntegrationPollerDemoApplication.class, args);
    }

    /**
     * 定义一个基于队列的通道（QueueChannel）
     * 这是一个 PollableChannel，会缓存消息直到被轮询出来
     */
    @Bean
    public PollableChannel queueChannel() {
        return new QueueChannel();
    }

    /**
     * 配置默认轮询器（Poller）
     * 每 2 秒轮询一次，最多处理 1 条消息
     * Poller 是专为 PollableChannel 准备的
     */
//    @Bean(name = PollerMetadata.DEFAULT_POLLER)
//    public PollerMetadata defaultPoller() {
//        PollerMetadata pollerMetadata = new PollerMetadata();
//        pollerMetadata.setTrigger(new PeriodicTrigger(Duration.of(2, ChronoUnit.SECONDS))); // 每2秒轮询
//        pollerMetadata.setMaxMessagesPerPoll(1);              // 每次1条
//        return pollerMetadata;
//    }

    /**
     * 消费 queueChannel 中的消息（轮询方式）
     * 由于 queueChannel 是 PollableChannel，必须有 Poller 才能激活消费
     */
    @ServiceActivator(inputChannel = "queueChannel", poller = @Poller(fixedRate = "2000", maxMessagesPerPoll = "1"))
    public void consumeMessage(String payload) {
        System.out.println("接收到消息（轮询方式）： " + payload);
    }

    // 应用启动后，通过命令行 Runner 向通道发送一条消息
    @Bean
    public CommandLineRunner sendRunner(MessageChannel queueChannel) {
        return args -> {
            Scanner scanner = new Scanner(System.in);
            System.out.println("请输入消息（输入 exit 退出）：");

            while (true) {
                System.out.print("> ");
                String line = scanner.nextLine();
                if ("exit".equalsIgnoreCase(line)) {
                    System.out.println("程序结束");
                    System.exit(0);  // 也可以优雅退出
                }

                queueChannel.send(new GenericMessage<>(line));
            }
        };
    }

}
